package revontuli.aMHD.UIhelpers;

import java.util.ArrayList;

import revontuli.aMHD.dataclasses.Stop;
import revontuli.aMHD.R;
import revontuli.aMHD.StopScheduleAct;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;

public class StopListAdapter extends BaseAdapter implements OnClickListener {
	private ArrayList<Stop> mList = new ArrayList<Stop>();
	private Context mContext;

	public StopListAdapter(Context context, ArrayList<Stop> list) {
		this.mContext = context;
		this.mList = list;
	}
	
	@Override
	public int getCount() {
		return mList.size();
	}

	@Override
	public Object getItem(int pos) {
		return mList.get(pos);
	}

	@Override
	public long getItemId(int pos) {
		return pos;
	}

	@Override
	public View getView(int pos, View mView, ViewGroup mViewGroup) {
		Stop mStop = mList.get(pos);
		
		if (mView == null) {
			LayoutInflater mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			mView = mInflater.inflate(R.layout.stoplistitem, null);
		}
		
		LinearLayout riadok = (LinearLayout) mView.findViewById(R.id.StopListItem);
		riadok.setOnClickListener(this);
		riadok.setTag(mStop.id);
		
		TextView mName = (TextView) mView.findViewById(R.id.StopListItemText);
		mName.setText(mStop.name);
		
		RatingBar mStar = (RatingBar) mView.findViewById(R.id.StopListItemStar);
		mStar.setOnTouchListener(mStarListener);
		mStar.setTag(mStop.id);
		if (mStop.favourite == true) {
			mStar.setRating(1);
		} else {
			mStar.setRating(0);
		}
		return mView;
	}
	
	
	private OnTouchListener mStarListener = new OnTouchListener() {
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			if (event.getAction() == MotionEvent.ACTION_UP) {
				RatingBar rb = (RatingBar) v;
				rb.setRating((rb.getRating()+1) % 2);
			}
			return true;
		}
	};

	@Override
	public void onClick(View v) {
		Intent in = new Intent(mContext, StopScheduleAct.class);
		in.putExtra("stopID", (Integer)v.getTag());
		mContext.startActivity(in);
	}

}
